# 引入必要的庫
from sklearn.datasets import load_iris
from sklearn.tree import DecisionTreeClassifier, plot_tree
from sklearn.model_selection import train_test_split
import matplotlib.pyplot as plt
# 加載鳶尾花數據集作為範例
iris = load_iris()
X, y = iris.data, iris.target
# 將數據集分為訓練集和測試集
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42)
# 創建決策樹分類器
clf = DecisionTreeClassifier()
# 使用訓練數據來訓練模型
clf.fit(X_train, y_train)
# 使用測試數據來評估模型性能
accuracy = clf.score(X_test, y_test)
print(f"準確率:{accuracy}")
# 繪製決策樹
plt.figure(figsize=(10, 7))
plot_tree(clf, filled=True, feature_names=iris.feature_names, class_names=iris.target_names)
plt.show()